package client

import (
	"fmt"

	"github.com/mars/internal/admin/core/domain"
)

// OrderView 用于前端展示的订单信息
type OrderView struct {
	ID             string            `json:"_id,omitempty"`
	OrderNo        string            `json:"orderNo"`
	OpenID         string            `json:"openid"`
	Phone          string            `json:"phone"`
	Items          []OrderItemView   `json:"items"`
	OriginalAmount int               `json:"originalAmount"` // 原始金额（分）
	DiscountAmount int               `json:"discountAmount"` // 折扣金额（分）
	TotalAmount    int               `json:"totalAmount"`    // 实际支付金额（分）
	PaymentMethod  string            `json:"paymentMethod"`
	PaymentTime    *string           `json:"paymentTime,omitempty"`
	Status         string            `json:"status"`
	IsVipOrder     bool              `json:"isVipOrder"`
	VipInfo        *OrderVipInfoView `json:"vipInfo,omitempty"`
	Address        *domain.Address   `json:"address,omitempty"`
	Remark         string            `json:"remark,omitempty"`
	CreateTime     string            `json:"createTime"`
	UpdateTime     string            `json:"updateTime"`
	// 计算字段
	HasPhysicalItems  bool   `json:"hasPhysicalItems"`  // 是否包含实物商品
	HasTicketItems    bool   `json:"hasTicketItems"`    // 是否包含门票商品
	HasVipItems       bool   `json:"hasVipItems"`       // 是否包含VIP商品
	StatusText        string `json:"statusText"`        // 状态文本
	PaymentMethodText string `json:"paymentMethodText"` // 支付方式文本
}

// OrderItemView 订单项视图
type OrderItemView struct {
	ProductID        string           `json:"productId"`
	ProductName      string           `json:"productName"`
	ProductImage     string           `json:"productImage"`
	ProductType      string           `json:"productType"`
	OriginalPrice    int              `json:"originalPrice"`    // 原价（分）
	Price            int              `json:"price"`            // 实际价格（分）
	Quantity         int              `json:"quantity"`         // 数量
	OriginalSubtotal int              `json:"originalSubtotal"` // 原小计（分）
	Subtotal         int              `json:"subtotal"`         // 实际小计（分）
	HasVipDiscount   bool             `json:"hasVipDiscount"`   // 是否有VIP折扣
	VipDiscount      *VipDiscountView `json:"vipDiscount,omitempty"`
	TicketType       string           `json:"ticketType,omitempty"` // 门票类型
	// 计算字段
	DiscountAmount  int     `json:"discountAmount"`  // 单项折扣金额
	DiscountRate    float64 `json:"discountRate"`    // 折扣率
	ProductTypeText string  `json:"productTypeText"` // 商品类型文本
}

// VipDiscountView VIP折扣视图
type VipDiscountView struct {
	Type  string `json:"type"`  // 折扣类型
	Value int    `json:"value"` // 折扣值
	Text  string `json:"text"`  // 折扣描述文本
}

// OrderVipInfoView 订单VIP信息视图 (避免与user_view中的VipInfoView冲突)
type OrderVipInfoView struct {
	Type     string `json:"type"`     // VIP类型
	TypeText string `json:"typeText"` // VIP类型文本
}

// OrderStatsView 订单统计视图
type OrderStatsView struct {
	TotalOrders         int64             `json:"totalOrders"`         // 总订单数
	TotalAmount         int64             `json:"totalAmount"`         // 总金额（分）
	TotalDiscountAmount int64             `json:"totalDiscountAmount"` // 总折扣金额（分）
	OrdersByStatus      map[string]int64  `json:"ordersByStatus"`      // 按状态统计
	OrdersByPayment     map[string]int64  `json:"ordersByPayment"`     // 按支付方式统计
	OrdersByType        map[string]int64  `json:"ordersByType"`        // 按商品类型统计
	VipOrderCount       int64             `json:"vipOrderCount"`       // VIP订单数
	VipDiscountAmount   int64             `json:"vipDiscountAmount"`   // VIP折扣总金额
	AvgOrderAmount      int               `json:"avgOrderAmount"`      // 平均订单金额（分）
	TopProducts         []ProductStatView `json:"topProducts"`         // 热销商品
	// 计算字段
	VipOrderRate float64 `json:"vipOrderRate"` // VIP订单占比
	DiscountRate float64 `json:"discountRate"` // 整体折扣率
}

// ProductStatView 商品统计视图
type ProductStatView struct {
	ProductID   string `json:"productId"`
	ProductName string `json:"productName"`
	OrderCount  int64  `json:"orderCount"`  // 订单数
	TotalAmount int64  `json:"totalAmount"` // 总金额
}

// ToOrderView 将domain.Order转换为OrderView
func ToOrderView(order *domain.Order) *OrderView {
	if order == nil {
		return nil
	}

	view := &OrderView{
		ID:                order.ID,
		OrderNo:           order.OrderNo,
		OpenID:            order.OpenID,
		Phone:             order.Phone,
		Items:             ToOrderItemViewList(order.Items),
		OriginalAmount:    order.OriginalAmount,
		DiscountAmount:    order.DiscountAmount,
		TotalAmount:       order.TotalAmount,
		PaymentMethod:     string(order.PaymentMethod),
		Status:            string(order.Status),
		IsVipOrder:        order.IsVipOrder,
		VipInfo:           ToVipInfoView(order.VipInfo),
		Address:           order.Address,
		Remark:            order.Remark,
		CreateTime:        formatTimestamp(order.CreateTime, TimeFormatDateTime),
		UpdateTime:        formatTimestamp(order.UpdateTime, TimeFormatDateTime),
		StatusText:        getStatusText(order.Status),
		PaymentMethodText: getPaymentMethodText(order.PaymentMethod),
	}

	// 设置支付时间
	if order.PaymentTime != nil {
		paymentTimeStr := formatTimestamp(*order.PaymentTime, TimeFormatDateTime)
		view.PaymentTime = &paymentTimeStr
	}

	// 计算字段
	view.HasPhysicalItems = hasItemsOfType(order.Items, domain.ProductTypePhysical)
	view.HasTicketItems = hasItemsOfType(order.Items, domain.ProductTypeTicket)
	view.HasVipItems = hasItemsOfType(order.Items, domain.ProductTypeVIP)

	return view
}

// ToOrderViewList 将domain.Order列表转换为OrderView列表
func ToOrderViewList(orders []domain.Order) []OrderView {
	views := make([]OrderView, len(orders))
	for i, order := range orders {
		if view := ToOrderView(&order); view != nil {
			views[i] = *view
		}
	}
	return views
}

// ToOrderItemView 将domain.OrderItem转换为OrderItemView
func ToOrderItemView(item *domain.OrderItem) *OrderItemView {
	if item == nil {
		return nil
	}

	view := &OrderItemView{
		ProductID:        item.ProductID,
		ProductName:      item.ProductName,
		ProductImage:     item.ProductImage,
		ProductType:      string(item.ProductType),
		OriginalPrice:    item.OriginalPrice,
		Price:            item.Price,
		Quantity:         item.Quantity,
		OriginalSubtotal: item.OriginalSubtotal,
		Subtotal:         item.Subtotal,
		HasVipDiscount:   item.HasVipDiscount,
		VipDiscount:      ToVipDiscountView(item.VipDiscount),
		TicketType:       item.TicketType,
		ProductTypeText:  getProductTypeText(item.ProductType),
	}

	// 计算折扣金额和折扣率
	view.DiscountAmount = item.OriginalSubtotal - item.Subtotal
	if item.OriginalSubtotal > 0 {
		view.DiscountRate = float64(view.DiscountAmount) / float64(item.OriginalSubtotal) * 100
	}

	return view
}

// ToOrderItemViewList 将domain.OrderItem列表转换为OrderItemView列表
func ToOrderItemViewList(items []domain.OrderItem) []OrderItemView {
	views := make([]OrderItemView, len(items))
	for i, item := range items {
		if view := ToOrderItemView(&item); view != nil {
			views[i] = *view
		}
	}
	return views
}

// ToVipDiscountView 将domain.VipDiscount转换为VipDiscountView
func ToVipDiscountView(vipDiscount *domain.VipDiscount) *VipDiscountView {
	if vipDiscount == nil {
		return nil
	}

	view := &VipDiscountView{
		Type:  string(vipDiscount.Type),
		Value: vipDiscount.Value,
		Text:  getVipDiscountText(vipDiscount.Type, vipDiscount.Value),
	}

	return view
}

// ToVipInfoView 将domain.VipInfo转换为VipInfoView
func ToVipInfoView(vipInfo *domain.VipInfo) *OrderVipInfoView {
	if vipInfo == nil {
		return nil
	}

	view := &OrderVipInfoView{
		Type:     string(vipInfo.Type),
		TypeText: getVipTypeText(domain.VipType(vipInfo.Type)),
	}

	return view
}

// ToOrderStatsView 将domain.OrderStats转换为OrderStatsView
func ToOrderStatsView(stats *domain.OrderStats) *OrderStatsView {
	if stats == nil {
		return nil
	}

	view := &OrderStatsView{
		TotalOrders:         stats.TotalOrders,
		TotalAmount:         stats.TotalAmount,
		TotalDiscountAmount: stats.TotalDiscountAmount,
		OrdersByStatus:      stats.OrdersByStatus,
		OrdersByPayment:     stats.OrdersByPayment,
		OrdersByType:        stats.OrdersByType,
		VipOrderCount:       stats.VipOrderCount,
		VipDiscountAmount:   stats.VipDiscountAmount,
		AvgOrderAmount:      stats.AvgOrderAmount,
		TopProducts:         ToProductStatViewList(stats.TopProducts),
	}

	// 计算VIP订单占比
	if stats.TotalOrders > 0 {
		view.VipOrderRate = float64(stats.VipOrderCount) / float64(stats.TotalOrders) * 100
	}

	// 计算整体折扣率
	if stats.TotalAmount > 0 {
		view.DiscountRate = float64(stats.TotalDiscountAmount) / float64(stats.TotalAmount) * 100
	}

	return view
}

// ToProductStatViewList 将domain.ProductStat列表转换为ProductStatView列表
func ToProductStatViewList(stats []domain.ProductStat) []ProductStatView {
	views := make([]ProductStatView, len(stats))
	for i, stat := range stats {
		views[i] = ProductStatView{
			ProductID:   stat.ProductID,
			ProductName: stat.ProductName,
			OrderCount:  stat.OrderCount,
			TotalAmount: stat.TotalAmount,
		}
	}
	return views
}

// 辅助函数

// hasItemsOfType 检查订单是否包含指定类型的商品
func hasItemsOfType(items []domain.OrderItem, productType domain.ProductType) bool {
	for _, item := range items {
		if item.ProductType == productType {
			return true
		}
	}
	return false
}

// getStatusText 获取订单状态文本
func getStatusText(status domain.OrderStatus) string {
	statusMap := map[domain.OrderStatus]string{
		domain.OrderStatusPending:   "待支付",
		domain.OrderStatusPaid:      "已支付",
		domain.OrderStatusShipped:   "已发货",
		domain.OrderStatusDelivered: "已收货",
		domain.OrderStatusCompleted: "已完成",
		domain.OrderStatusCancelled: "已取消",
		domain.OrderStatusRefunded:  "已退款",
		domain.OrderStatusRefunding: "退款中",
	}
	return statusMap[status]
}

// getPaymentMethodText 获取支付方式文本
func getPaymentMethodText(method domain.PaymentMethod) string {
	methodMap := map[domain.PaymentMethod]string{
		domain.PaymentMethodWechat: "微信支付",
		domain.PaymentMethodAlipay: "支付宝",
	}
	return methodMap[method]
}

// getProductTypeText 获取商品类型文本
func getProductTypeText(productType domain.ProductType) string {
	typeMap := map[domain.ProductType]string{
		domain.ProductTypeVIP:      "VIP会员",
		domain.ProductTypeTicket:   "入场券",
		domain.ProductTypePhysical: "实物商品",
	}
	return typeMap[productType]
}

// getVipDiscountText 获取VIP折扣描述文本
func getVipDiscountText(discountType domain.DiscountType, value int) string {
	switch discountType {
	case domain.DiscountTypePercent:
		return fmt.Sprintf("享受%d%%折扣", 100-value)
	case domain.DiscountTypeAmount:
		return fmt.Sprintf("减免%d分", value)
	default:
		return ""
	}
}

// getVipTypeText 获取VIP类型文本
func getVipTypeText(vipType domain.VipType) string {
	typeMap := map[domain.VipType]string{
		domain.VipTypeMonthly: "月度会员",
		domain.VipTypeYearly:  "年度会员",
	}
	return typeMap[vipType]
}
